package mapred.example.model;

import java.util.Arrays;
import java.util.List;

import util.FieldUtil;

public class Anchor {

    private int type;

    private String weight;

    private List<String> text;

    private Anchor(int type, String weight, String... text) {
        this.type = type;
        this.weight = weight;
        this.text = Arrays.asList(text);
    }

    public Anchor(String s) {
        int pos = s.indexOf('\t');
        if (pos == 0) {
            type = 0;
        } else {
            type = Integer.parseInt(s.substring(0, pos));
            pos = s.indexOf('\t', pos + 1);
        }

        text = Arrays.asList(s.substring(pos + 1).split("\t"));
        weight = text.remove(0);
    }

    public int getType() {
        return type;
    }

    public String getWeight() {
        return weight;
    }

    public List<String> getText() {
        return text;
    }

    public String getStr() {
        StringBuilder sb = new StringBuilder();
        sb.append(type);
        for (String t : text) {
            sb.append("\t");
            sb.append(t);
        }
        return sb.toString();
    }

    public long getLength() {
        return text.size();
    }

    public String toRLV(String[] query) {
        StringBuilder sb = new StringBuilder();
        sb.append("\2");
        sb.append(type);
        sb.append("\1");
        sb.append(weight);
        sb.append("\1");
        sb.append(text.size());
        for (String q : query) {
            List<Integer> poss = FieldUtil.getPositions(text, q);

            if (poss.size() > 0) {
                sb.append("\1");
                sb.append(q);
                sb.append("\t");
                sb.append(poss.size());
                for (int pos : poss) {
                    sb.append("\t");
                    sb.append(pos);
                    sb.append(" ");
                    sb.append("0");
                }
            }
        }
        return sb.toString();
    }

    public static Anchor newInstanceFromLink(Link link) {
        // TODO "(null)" is not good here.
        return new Anchor(link.getAnchorType(), "(null)", link.getText()
                .toArray(new String[0]));
    }

    public String encode() {
        return type + "\t" + weight + "\t" + FieldUtil.encode(this.getText());
    }

}
